const { resolve, isAbsolute, join } = require('path')
const { readdirSync, readFileSync } = require('fs')

const { validate } = require('schema-utils')
const globby = require('globby')
const webpack = require('webpack')
const { RawSource } = webpack.sources

const schema = require('./copy_schema.json')

class CopyWebpackPlugin {
  constructor(options = {}) {
    // 校验参数
    validate(schema, options, { name: 'CopyWebpackPlugin' })

    this.options = options

  }

  apply(compiler) {
    compiler.hooks.thisCompilation.tap('CopyWebpackPlugin', (compilation) => {
      compilation.hooks.additionalAssets.tapAsync('CopyWebpackPlugin', async (callback) => {
        const { from, ignore } = this.options
        const to = this.options.to ? this.options.to : '.'

        // 首先获取到所有需要复制的文件路径
        const context = compiler.options.context  // process.cwd() 文件运行路径 --> 运行指令的目录  context就是webpack的配置
        const fromPath = isAbsolute(from) ? from : resolve(context, from)

        // 获取到文件目录下的所有文件 - 忽略不需要复制的文件
        // const allPath = await globby(fromPath, {ignore})
        const allPath = readdirSync(fromPath)
        const assets = []
        allPath.map((file, i) => {
          if (ignore == file) {
            allPath.splice(i, 1)
          } else {
            // 创建RawSource
            const source = new RawSource(readFileSync(join(fromPath, file)))
            assets.push({
              source,
              filename: file
            })
          }
        })

        assets.map(asset => {
          // 添加资源
          compilation.emitAsset(asset.filename, asset.source)
        })
        callback()
      })
    })
  }
}

module.exports = CopyWebpackPlugin